import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:mall/core/models/store_pin_gou.dart';
import 'package:mall/core/models/store_product_query.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/group/group_port_screen.dart';
import 'package:mall/components/clock_countdown.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 拼购商区
class ProductAreaPgScreen extends StatefulWidget {
  static const routeName = '/ProductAreaPgScreen';
  final Floor args;

  const ProductAreaPgScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _ProductAreaPgScreenState createState() => _ProductAreaPgScreenState();
}

class _ProductAreaPgScreenState extends State<ProductAreaPgScreen> {
  StorePinGou _storePinGou;
  RefreshController _refreshController;
  int _pageIndex;
  String _error;
  StoreProductQuery _storeProductQuery;
  final List<Product> _list = [];

  @override
  void initState() {
    super.initState();
    _storePinGouRefresh();
    _onRefresh();
    _refreshController = RefreshController();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("${widget.args.linkStoreAreaName}"),
      ),
      body: _error == null && _storeProductQuery == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _storeProductQuery == null
              ? Center(
                  child: Text('$_error'),
                )
              : buildBody(),
    );
  }

  Widget buildBody() {
    return SmartRefresher(
      controller: _refreshController,
      enablePullUp: _storeProductQuery.productList.length == 10,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: SingleChildScrollView(
        padding: EdgeInsets.all(8.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (_storePinGou != null) _buildHeader(),
            SizedBox(height: 8.w),
            Wrap(
              spacing: 8.w,
              runSpacing: 8.w,
              children: List.generate(_list.length, (index) => _buildItem(index)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "${widget.args.title}",
          style: TextStyle(fontSize: 16.w),
        ),
        SizedBox(height: 8.w),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("第 ${_storePinGou.teamCode} 期"),
            ClockCountdown(
              endTime: _storePinGou.startTime.add(Duration(minutes: _storePinGou.maxTimeLen)),
              fontSize: 13.sp,
              onEnd: _onEnd,
            ),
          ],
        ),
      ],
    );
  }

  /// 倒计时结束
  void _onEnd() async {
    // 是否刷新
    if (!_storePinGou.refresh) {
      return;
    }
    // 延迟3秒
    await Future.delayed(Duration(seconds: 3));
    if (!mounted) {
      return;
    }
    // 立即刷新
    _storePinGouRefresh();
  }

  Widget _buildItem(int index) {
    final product = _list[index];
    return GestureDetector(
      onTap: () => _onTapItem(product),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        width: ((375 - 8 * 3) ~/ 2).w,
        height: 240.w,
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.vertical(
                top: Radius.circular(4.w),
              ),
              child: ImageNetwork(
                url: "${product.productImage}",
                width: ((375 - 8 * 3) ~/ 2).w,
                height: ((375 - 8 * 3) ~/ 2).w,
              ),
            ),
            Align(
              alignment: Alignment.topLeft,
              child: Padding(
                padding: EdgeInsets.fromLTRB(
                  4.w,
                  4.w,
                  4.w,
                  0,
                ),
                child: Text(
                  "${product.productName}",
                  style: TextStyle(fontSize: 12.w),
                  maxLines: 2,
                ),
              ),
            ),
            Spacer(),
            Align(
              alignment: Alignment.bottomRight,
              child: Padding(
                padding: EdgeInsets.fromLTRB(
                  4.w,
                  0,
                  4.w,
                  4.w,
                ),
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Theme.of(context).primaryColor,
                    ),
                    borderRadius: BorderRadius.circular(12.w),
                  ),
                  child: Text(
                    "拼购",
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 12.sp,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 点击商品
  void _onTapItem(Product product) {
    Navigator.of(context).pushNamed(
      GroupPortScreen.routeName,
      arguments: GroupPortScreenArgs(product.miaId, product.productImage),
    );
  }

  /// 拼购信息刷新
  void _storePinGouRefresh() async {
    final api = context.read<Api>();
    try {
      final storePinGou = await api.groupPurchaseRefresh(widget.args);
      if (!mounted) {
        return;
      }
      if (storePinGou.startTime == null) {
        throw '数据错误';
      }
      setState(() {
        _storePinGou = storePinGou;
      });
    } on DioError catch (e) {
      debugPrint('${e.message}');
    } catch (e) {
      debugPrint('$e');
    }
  }

  /// 第一页
  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final storeProductQuery = await api.storeProductQueryNew(
        widget.args.linkStoreId,
        null,
        widget.args.linkStoreAreaId,
        null,
        _pageIndex,
        widget.args.productPrice,
      );
      if (!mounted) {
        return;
      }
      if (storeProductQuery.curPinGouQiShu == null) {
        throw "数据错误";
      }
      _refreshController.refreshCompleted();
      setState(() {
        _storeProductQuery = storeProductQuery;
        _list.clear();
        _list.addAll(storeProductQuery.productList);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      setState(() {
        _error = e.message;
      });
    } catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      setState(() {
        _error = '$e';
      });
    }
  }

  /// 更多页
  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final storeProductQuery = await api.storeProductQueryNew(
        widget.args.linkStoreId,
        null,
        widget.args.linkStoreAreaId,
        null,
        _pageIndex,
        widget.args.productPrice,
      );
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        _storeProductQuery = storeProductQuery;
        _list.addAll(storeProductQuery.productList);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.loadFailed();
      EasyLoading.showToast("${e.message}");
    }
  }
}
